//
//  BSyContentView.swift
//  BMort_SwiftUI
//
//  Created by anscen on 2022/9/1.
//

import SwiftUI

struct BSyContentView: View {
    @State var money :String = ""
    @State var month :String = ""
    @State var rate  :String = ""
    @State var discount  :String = ""
    @State var index :Int    = 0
    private var listData :[String] = ["等额本息","等额本金"]
    var body: some View {
        VStack {
            HStack {
                Picker(selection:$index) {
                    ForEach(0..<listData.count) { index in
                        Text(self.listData[index]).tag(index)
                    }
                } label: {
                    
                }.pickerStyle(SegmentedPickerStyle()).frame(width: 150, height: 36, alignment: .center)
            }
            List {
                BTextFieldView(title: moya.money, placeholder: "输入贷款金额", text: $money)
                BTextFieldView(title: moya.month, placeholder: "输入贷款月数", text: $month)
                BRateView.init(state: .syMort, title: moya.rate, rate: $rate)
                BTextFieldView(title: moya.discount, placeholder: "输入贷款折扣", text: $discount)
                BComputerView {
                    BMoreContentView(model: self.getMortGage())
                }
            }.padding(EdgeInsets.init(top: 5, leading: 0, bottom: 5, trailing: 0)).listStyle(.insetGrouped)
        }.onAppear {
            self.loadData()
        }
    }
    func getMortGage() ->BMortgage{
        debugPrint("BMoreContentView")
        var item = BMortgage()
        item.identy = "\(BAppMortState.syMort.rawValue)"
        item.month = self.month
        item.symoney = self.money
        item.syrate  = self.rate
        item.discount = self.discount
        item.repay = self.index == 0 ? .rate : .capital
        
        if self.month.count > 0 && self.money.count > 0 && self.rate.count > 0 && self.discount.count > 0{
            BMortData.updateData(model: item) { success in

            }
        }
        return item
    }
    func loadData(){
        if self.money.count == 0{
            BMortData.getData(identy: "\(BAppMortState.syMort.rawValue)") { model in
                if let item = model{
                    self.money = item.symoney ?? ""
                    self.month = item.month ?? ""
                    self.rate = item.syrate ?? ""
                    self.index = item.repay == .rate ? 0 : 1
                    self.discount = item.discount  ?? ""
                }
            }
        }
    }
}
